package android.gpsmessenger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.AlertDialog;
import android.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.ViewGroup;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CurrentTripFragment extends Fragment
{
	private Button new_trip_button, choose_trip_button, location_button;
	private Button frequency_button, record_button, upload_button;
	private Button help_button, sos_button, message1_button, message2_button;

	private TripManager tripManager;
	private TripList trips;
	private Trip selectedTrip;
	private int tripLocationCount = 0;
	private boolean tripSelected = false;
	private boolean recordSelected = false;
	private EditText trip_name;
	private int selectedFrequency;
	private String tripName;
	
	private String[] frequencies = {"2 sec", "30 sec", "1 min", "2 min", 
    		"5 min", "10 min", "15 min", "30 min", "60 min"};
    
	private MessengerLocator messengerLocator;
	private Messenger emailMessenger;
	private Messenger textMessenger;
	private MessageList messages;
	
	private ContactList contacts;
	private ContactManager contactManager;
	
	private Timer myTimer;

    private android.location.LocationManager _locationManager;
    /* Timer method adds last known location to trip */
	private void TimerMethod()
	{
	    //This method is called directly by the timer
	    //and runs in the same thread as the timer.
//        Timer_Tick.run();
    	if(_locationManager != null)
    	{
	    	Location loc = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
	    	
	    	if(loc != null)
	    	{
		    	selectedTrip.addLocation(new android.gpsmessenger.Location(loc.getLatitude(), loc.getLongitude()));	    		    	
		    	tripManager.save(trips);
	    	}
    	}
	}
	
	public void onCreate (Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		selectedFrequency = -1;
		tripManager = new TripManager(getActivity());
		selectedTrip = new Trip();
		trips = new TripList();
		
		tripName = getActivity().getIntent().getStringExtra("selected_name");
		Log.i("selectedTrip", "selectedTrip: " + tripName);
		
		messages = new MessageList();
		messages.load(getActivity().getFilesDir().getAbsolutePath() + "/messages.xml");
		messengerLocator = new MessengerLocator();
		textMessenger = messengerLocator.createMessenger(getActivity(), "text");
		emailMessenger = messengerLocator.createMessenger(getActivity(), "email");
		
		contactManager = new ContactManager(getActivity());
		contacts = contactManager.load();
		
		android.app.Activity activity = getActivity();
		_locationManager = (LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);
	}
		
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
	{
		return inflater.inflate(R.layout.fragment_current_trip, container, false);
	}
	
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
	{
		inflater.inflate(R.menu.fragment_home_menu, menu);
	}
	
	public boolean onOptionsItemSelected (MenuItem item) 
	{
        Intent intent = new Intent(getActivity(), MainActivity.class);
		if (item.getItemId() == R.id.menu_home) 
		{
	        getActivity().startActivity(intent);
		}

		return true;
	}
	
	public void onResume() 
	{
		super.onResume();

		if (tripName != null)
		{
			String docId = selectedTrip.getFusionTableDocId();
			boolean isDirty = (docId != null && !docId.isEmpty());
			if(isDirty)
				tripManager.save(trips);
			
			trips = tripManager.load();
			selectedTrip = trips.getTrip(tripName);
			tripSelected = true;
			
			buttonsEnabled(true);
			trip_name.setText(selectedTrip.getName());
		
        	Toast.makeText(getActivity(), String.format("Locations in Trip: %1d", selectedTrip.getLocations().size()),
        			Toast.LENGTH_LONG ).show();
		}
	}
	
	public void onPause() 
	{
	    super.onPause(); 
	}	
		
	@Override
	public void onActivityCreated(Bundle savedInstanceState) 
	{
		super.onActivityCreated(savedInstanceState);
		getActivity().setContentView(R.layout.fragment_current_trip);
		
		trip_name = (EditText) getActivity().findViewById(R.id.tripName);
		new_trip_button = (Button) getActivity().findViewById(R.id.new_trip_button);
		choose_trip_button = (Button) getActivity().findViewById(R.id.choose_trip_button);
		record_button = (Button) getActivity().findViewById(R.id.record_button);
		upload_button = (Button) getActivity().findViewById(R.id.upload_button);
		frequency_button = (Button) getActivity().findViewById(R.id.frequency_button);
		help_button = (Button) getActivity().findViewById(R.id.help_button);
		sos_button = (Button) getActivity().findViewById(R.id.sos_button);
		message1_button = (Button) getActivity().findViewById(R.id.send_message1_button);
		message2_button = (Button) getActivity().findViewById(R.id.send_message2_button);
		location_button = (Button) getActivity().findViewById(R.id.send_location_button);
		
		new_trip_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				Intent newTripIntent = new Intent(getActivity().getApplicationContext(), TripProfileActivity.class);		
			    startActivity(newTripIntent);
			}
 		});		

		choose_trip_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				Intent tripListIntent = new Intent(getActivity().getApplicationContext(), TripListActivity.class);	
			    startActivity(tripListIntent);
			}
 		});	
	
		upload_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				if(myTimer != null)
 					myTimer.cancel(); //stop recording, so we avoid concurrency exception while trying 
 				
 				String tripId = selectedTrip.getFusionTableDocId();
 				if(tripId != null && !tripId.isEmpty())
 				{
		        	Toast.makeText(getActivity(), "Trip already uploaded as : " + tripId,
		        			Toast.LENGTH_LONG ).show();
		        	return; 					
 				}
 					
 				android.app.Activity activity = getActivity();
// 				LocationManager locationManager = (LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);

 					Location location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

// 					List<Track> tracks = myTracksProviderUtils.getAllTracks();
// 					Toast.makeText(LbsGeocodingActivity.this, String.format("Num Tracks: %1d", tracks.size()),
// 								Toast.LENGTH_LONG).show();

 					//dial();
 					  AccountManager mgr = AccountManager.get(activity.getApplicationContext());
// 					  Account[] accounts = AccountManager.get(this).getAccountsByType(Constants.ACCOUNT_TYPE);
 					  Account[] accounts = mgr.getAccountsByType("com.google");
 					  
 				      if(accounts.length > 0)	    	  
 				      {
 				    	 AccountManagerFuture<Bundle> accountManagerFuture = mgr.getAuthToken(accounts[0], "fusiontables", null, activity, null, null);
 				    			 //.getAuthToken(accounts[0], "fusiontables", null, this, null, null);
 				    	   Bundle authTokenBundle = null;
 						try {
 							try {
 								Thread.sleep(500);
 							} catch (InterruptedException e) {
 								// TODO Auto-generated catch block
 								e.printStackTrace();
 							}
 							authTokenBundle = accountManagerFuture.getResult();
 						} catch (OperationCanceledException e) {
 							// TODO Auto-generated catch block
 							e.printStackTrace();
 						} catch (AuthenticatorException e) {
 							// TODO Auto-generated catch block
 							e.printStackTrace();
 						} catch (IOException e) {
 							// TODO Auto-generated catch block
 							e.printStackTrace();
 						}
 						if(authTokenBundle != null)
 						{
 							String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
 				    	   mgr.invalidateAuthToken(accounts[0].type, authToken);
 						}  
// 				    	  mgr.getAuthToken(accounts[0], SendFusionTablesUtils.SERVICE, false);
 				      }

 	 					if (location == null)
 	 						location = new android.location.Location("asdsad");//android.location.Location.CREATOR()
 				      
 					if (location != null) {
 						String message = String.format(
 								"Current Location \n Longitude: %1$s \n Latitude: %2$s",
 								location.getLongitude(), location.getLatitude()
 						);
 						//HACK - provide the backend Activity/ASyncTask with the current trip
 						com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesActivity.MyTrip = selectedTrip;
 						Intent launch = new Intent(activity, com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesActivity.class);
 						startActivity(launch);
 						//new com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesActivity();
 						
 						
 						//sendSMS("5558675309", message);
 						return;

 			/*			Toast.makeText(LbsGeocodingActivity.this, message,
 								Toast.LENGTH_LONG).show();
 			*/ 					
 				}   
			}
 		});	
		

		
		record_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
  			    Button button = (Button) getActivity().findViewById(R.id.record_button);

  			    if(myTimer != null)
 				{
 					myTimer.cancel();
 					if(button != null)
 						button.setText("Record");
// 	  			    button.setEnabled(false);
 					myTimer = null;

 					int numTotal = selectedTrip.getLocations().size(), numNew = numTotal - tripLocationCount;
		        	Toast.makeText(getActivity(), String.format("New Locations: %1d (total %1d)", numNew, numTotal),
		        			Toast.LENGTH_LONG ).show();

 				}
  			    else
  			    { 				
	 			    myTimer = new Timer();
	 			   
	 			   tripLocationCount = selectedTrip.getLocations().size();
	 			   int frequency = selectedFrequency + 1;
	 			   int period_ms = (frequency > 0) ? frequency * 5000 : 5000; /* multiples of 5 sec*/
//	 			   myTimer.schedule(TimerMethod, 0, (selectedFrequency + 1) * 5000 /* multiples of 5 sec*/);
	 			   myTimer.schedule(new TimerTask() {
	 			        @Override
	 			        public void run() {
	 			            TimerMethod();
	 			        }
	
	 			    }, 0, period_ms );
	
	 			   if(button != null)
	 				   button.setText("End");
  			    }
			}
 			
 		});	
		
		sos_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				AlertDialog.Builder alert_box = new AlertDialog.Builder(getActivity());
 				alert_box.setIcon(R.drawable.ic_action_search);
 				alert_box.setMessage("Are you sure you want to ask\"" + getRecipients("sos", false)[0] + "\" for SOS-Help");
 				alert_box.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
 				   
 				   @Override
 				   public void onClick(DialogInterface dialog, int which) {
 					  //textMessenger.send(getRecipients("sos", false), "sos", tripManager.getSOSLocationMessage());
 			        	Toast.makeText(getActivity(), "HELP!!!",
 			        			Toast.LENGTH_LONG ).show();

 				   }
 				  });
 				alert_box.setNegativeButton("No", null);
 				alert_box.show();
			}
 		});	
		
		help_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				textMessenger.send(getRecipients("help", false), "help", messages.getHelpMessage().getMessage());
			}
 		});	
		
		message1_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				textMessenger.send(getRecipients("friend", false), "message1", messages.getMessage1().getMessage());
			}
 		});	
		
		message2_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				textMessenger.send(getRecipients("friend", false), "message2", messages.getMessage2().getMessage());
			}
 		});	
		
		location_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				String locationMessage = tripManager.getLocationMessage(selectedTrip);
 				if(locationMessage != null)
 					emailMessenger.send(getRecipients("friend", true), "Check my Location", locationMessage);
 				else
 				{
 					Location location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
 					emailMessenger.send(getRecipients("friend", true), "Check my Location", tripManager.getLocationMessage(location));
				}
			}
 		});	
		
		frequency_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
 				alt_bld.setTitle("Select Record Frequency");

 				alt_bld.setSingleChoiceItems(frequencies , -1,
 				new DialogInterface.OnClickListener() 
 				{
 					public void onClick(DialogInterface dialog, int item) 
 					{
 						selectedFrequency = item;
 					}
 				});
 				
 				alt_bld.setPositiveButton("OK", new DialogInterface.OnClickListener() 
 				{
 					@Override
 					public void onClick(DialogInterface dialog, int which) 
 					{
 						Toast.makeText(getActivity().getApplicationContext(), "Selected record frequency: " + frequencies[selectedFrequency], Toast.LENGTH_SHORT).show();
 						dialog.dismiss();
 					}
 				});
 				
 				alt_bld.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
 				{
 					@Override
 					public void onClick(DialogInterface dialog, int which) 
 					{
 						dialog.dismiss();
 					}
 				});
 				
 				AlertDialog alert = alt_bld.create();
 				alert.show();
			}
 		});	

		buttonsEnabled(false);
    }
	
	public String[] getRecipients (String type, boolean supportsEmail)
	{
		List<Contact> recipients = new ArrayList<Contact>(100);
		List<String> contactInfo = new ArrayList<String>(100);
		String[] to = new String[contactInfo.size()]; //{"5556"};
		
		if (type.equals("help"))
			recipients = getHelpContactList();
		else if (type.equals("friend"))
			recipients = getFriendContactList();
		else if (type.equals("sos"))
			recipients.add(getSOSContact());
		
		if (supportsEmail)
			contactInfo = getEmailList(recipients);
		else 
			contactInfo = getPhoneList(recipients);
		
		to = contactInfo.toArray(new String[recipients.size()]);

		return to;
	}
	
	private List<String> getEmailList(List<Contact> recipients)
	{
		List<String> list = new ArrayList<String>(100);
		for (Contact c : recipients)
			list.add(c.getEmail());
		return list;
	}
	
	private List<String> getPhoneList(List<Contact> recipients)
	{
		List<String> list = new ArrayList<String>(100);
		for (Contact c : recipients)
			list.add(c.getPhone());	
		return list;
	}	
	private List<Contact> getHelpContactList()
	{
		if (tripName != null )
			return selectedTrip.getContacts().getHelpContacts().getContactList();
		else
			return contactManager.load().getHelpContacts().getContactList();		
	}
	
	private List<Contact> getFriendContactList()
	{
		if (tripName != null )
			return selectedTrip.getContacts().getFriendContacts().getContactList();
		else
			return contactManager.load().getFriendContacts().getContactList();		
	}	
	
	private Contact getSOSContact()
	{
		if (tripName != null )
			return selectedTrip.getContacts().getSOSContact();
		else
			return contactManager.load().getSOSContact();
	}
	
	public String getSelectedFrequency()
	{
		if (selectedFrequency != -1)
		{
			Log.i("selectedFrequency", "selectedFrequency: " + frequencies[selectedFrequency]);
			return frequencies[selectedFrequency];
		}
		return null;
	}
	
	public void onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
	    MenuItem end = menu.findItem(R.id.menu_end);
		if (recordSelected ) {
			end.setEnabled(true);
		} else {
			end.setEnabled(false);	
		}
	}
	
	public void buttonsEnabled(boolean flag)
	{
		if  (flag)
		{
			frequency_button.setEnabled(true);
			upload_button.setEnabled(true);
			record_button.setEnabled(true);
		}
		else
		{
			frequency_button.setEnabled(false);
			upload_button.setEnabled(false);
			record_button.setEnabled(false);			
		}
	}
	
}

/*
public String[] getRecipients (String type)
	{
		List<Contact> recipients = new ArrayList<Contact>(100);
		List<String> contactInfo = new ArrayList<String>(100);
		String[] to = new String[contactInfo.size()]; //{"5556"};
		Contact sosContact;
		
		if (type.equals("help"))
		{
			if (tripName != null )
				recipients = selectedTrip.getContacts().getHelpContacts().getContactList();
			else
				recipients = contactManager.load().getHelpContacts().getContactList();
		}
		else if (type.equals("friend"))
		{
			if (tripName != null )
				recipients = selectedTrip.getContacts().getFriendContacts().getContactList();
			else
				recipients = contactManager.load().getFriendContacts().getContactList();
		}
		else if (type.equals("sos"))
		{
			if (tripName != null )
				sosContact = selectedTrip.getContacts().getSOSContact();
			else
				sosContact = contactManager.load().getSOSContact();
			
			recipients.add(sosContact);
		}	
		
		if (type.equals("friend"))
		{
			for (Contact c : recipients)
			{
				contactInfo.add(c.getEmail());
			}
		}
		else 
		{
			for (Contact c : recipients)
			{
				contactInfo.add(c.getPhone());
			}
		}
		
		to = contactInfo.toArray(new String[recipients.size()]);

		return to;
	}
	*/
